package com.example.interceptor;


import com.example.common.exception.BusinessException;
import com.example.passport.entity.User;
import com.example.passport.service.MenuService;
import com.example.passport.service.RoleService;
import com.example.passport.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashSet;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    TokenService tokenService;
    @Autowired
    RoleService roleService;
    @Resource
    MenuService menuService;


    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url=request.getRequestURI();
        HashSet<String> sites = new HashSet<String>();
//        sites.add("/passport/token/create");
//        sites.add("/passport/token/delete");
//        sites.add("/passport/user/updatePassword");
//        sites.add("/passport/user/whoami");
        sites.add("/front/messageLogging/list");
        if(sites.contains(url)){
            return true;
        }else {
            String token = request.getParameter("token");
            User user = tokenService.getUserByToken(token);
            UserContext.setUser(user);
            //跳过权限拦截

            if(user.getRoleId()==User.ADMIN_ID){
                return true;
            } else {
                if(menuService.Permission(user.getId(),url)==0 && !user.getName().equals("admin")){
                    throw new BusinessException("没有权限");
                }
            }
            return true;
        }

    }
}
